package com.watchmen.controller;

import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.watchmen.wechat.domain.WechatTemplateMsg;
import com.watchmen.wechat.pay.WeChatPay;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * @author kk
 * @Description 微信测试
 */
@RestController
@RequestMapping("/wechat")
public class WeChatPayTest {

	
	@Autowired
	WeChatPay weChatPay;
	
	@Autowired
	com.watchmen.wechat.news.TemplateMessage templateMessage;
	
	
	/**
	 * 扫码支付测试
	 * @return
	 */
	@GetMapping("/scanning")
	public Object scanningPayment(){
		JSONObject parse = weChatPay.scanningPay("1", "测试支付", "oIbwD1txKe4cnhEOr3SYEo1Tllyk");
		// 解析json
		String xml = parse.getStr("xml");
		// 生成二维码
		String codeUrl = JSONUtil.parseObj(xml).getStr("code_url");
		// 手机微信扫码支付后微信就会payCall方法了
		QrCodeUtil.generate(codeUrl, 300, 300, FileUtil.file("D:/logs/test.jpg"));
		return null;
	}

	
	/**
	 * jsApi支付测试
	 * @return
	 */
	@GetMapping("/jsApi")
	public Object jsApiPayment(){
		TreeMap<String, Object> parse = weChatPay.JSAPIPay("1", "测试支付", "oIbwD1txKe4cnhEOr3SYEo1Tllyk");
		System.out.println(parse);
		return parse;
	}
	
	
	/**
	 * 微信回调地址
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/payCall")
	public void payCall(HttpServletRequest request,HttpServletResponse response) throws Exception{
		System.out.println("微信回调用!");
		Map<String, Object> payResult = weChatPay.payResult(request);
		if(payResult.size() > 0){
			// 输出订单号
			System.out.println("out_trade_no："+payResult.get("out_trade_no").toString());
		}
	}
	
	
	
	/**
	 * 微信模板消息推送测试
	 * @throws Exception 
	 */
	@RequestMapping("/message")
	public void TemplateMessage() throws Exception{
		TreeMap<String,TreeMap<String,String>> params = new TreeMap<String,TreeMap<String,String>>();
		
		//根据具体模板参数组装
		params.put("first",WechatTemplateMsg.item("恭喜您的等级升级了！", "#000000"));
		params.put("first",WechatTemplateMsg.item("恭喜您的等级升级了！", "#000000"));
		params.put("keyword1",WechatTemplateMsg.item("明流清纯小菊花", "#000000"));
		params.put("keyword2",WechatTemplateMsg.item("一星魔法师", "#000000"));
		params.put("remark",WechatTemplateMsg.item("", "#000000"));
		
		String openId = "ocUdn0glU-9aXw5gETX8124x1Pdw";
		String url = "https://www.baidu.com";
		String sendOut = templateMessage.sendOut(params, Lists.newArrayList(openId), url);
		
		System.out.println("sendOut:"+sendOut);
	}
}
